#include <iostream>
#include <vector>

using namespace std;

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin) {
        int preend = pre.size() - 1;
        int vinend = vin.size() - 1;

        return buildBinaryTree(pre, vin, 0, preend, 0, vinend);
    }

private:
    TreeNode* buildBinaryTree(vector<int> pre, vector<int> vin, int prestart, int preend, int vinstart, int vinend){
        if(prestart > preend || vinstart > vinend)
            return NULL;

        TreeNode *root = new TreeNode(pre[prestart]);
        int index;
        for(index = vinstart; index <= vinend; index++){
            if(vin[index] == pre[prestart])
                break;
        }

        root->left = buildBinaryTree(pre, vin, prestart + 1, prestart + index - vinstart, vinstart, index - 1);
        root->right = buildBinaryTree(pre, vin, prestart + index - vinstart + 1, preend, index + 1, vinend);

        return root;
    }
};
